/* media-server.c */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>

#include "nbd-dev.h"
#include "nbd-server.h"
#include "igrs-server.h"

#include "ip.h"
#include "udp.h"
#include "tcp.h"
#include "dump.h"

/**
 * Handle SICHLD signal.
 */
static void sigchld_handler(int signo)
{
  signal(SIGCHLD, sigchld_handler);

  while (42) {
    int status;
    pid_t pid;

    pid = waitpid(-1, &status, WNOHANG);
    if (pid <= 0)
      break;

    // child 'pid' terminated with status 'status'
  }
}

/**
 * Create a child IGRS server.
 */
static int spawn_igrs_server(IGRS_SERVER *srv, NBD_SERVER *nbd_srv)
{
  pid_t pid;

  pid = fork();
  if (pid > 0) {
    nbd_server_close(nbd_srv);
    igrs_server_run(srv);
    _exit(0);
  }

  if (pid < 0) {
    dump_msg("** ERROR: can't fork()\n");
    return -1;
  }

  igrs_server_close(srv);
  return 0;
}

int main(int argc, char *argv[])
{
  IGRS_SERVER igrs_server;
  NBD_SERVER nbd_server;
  NBD_DEV dev;
  char *image_file;
  int i, debug;

  image_file = NULL;
  debug = 0;
  for (i = 1; i < argc; i++)
    if (strcmp(argv[i], "-d") == 0)
      debug = 1;
    else
      image_file = argv[i];

  if (! image_file) {
    printf("USAGE: %s [-d] image-file\n", argv[0]);
    return 0;
  }

  dump_set_output("-");

  // check if image can be opened
  if (nbd_dev_open_image(&dev, image_file) < 0) {
    printf("Can't open image file '%s'\n", image_file);
    return 1;
  }
  nbd_dev_close(&dev);

  // open NBD and IGRS servers
  if (nbd_server_open(&nbd_server) != 0)
    return 1;
  if (igrs_server_open(&igrs_server) != 0) {
    nbd_server_close(&nbd_server);
    return 1;
  }

  if (debug)
    dump_set_output("-");
  else
    dump_set_output(NULL);

  signal(SIGCHLD, sigchld_handler);

  if (spawn_igrs_server(&igrs_server, &nbd_server) != 0) {
    nbd_server_close(&nbd_server);
    igrs_server_close(&igrs_server);
    return 1;
  }
  nbd_server_run(&nbd_server, image_file);
  return 0;
}
